<template>
  <div class="container">
    <div class="card-container">
      <el-card class="card">
        <h2> 校园外卖商家登录系统 </h2>
        <div class="form">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="登录名：" prop="username">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input type="password" v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit('form')">登录</el-button>
              <el-button @click="onRegister">注册</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-card>
    </div>

  </div>
</template>

<script>
  export default {
    name: "Login",
    data(){
      return{
        form:{
          username:"",
          password:""
        },
        rules:{
          username:[
            {required:true,message: '请输入用户名',trigger:'blur'},
            {min:3,max:16,message:'长度在 3 到 16 个字符',trigger:'blur'}
          ],
          password:[
            {required:true,message: '请输入密码',trigger:'blur'},
            {min:6,max:16,message:'长度在 6 到 16 个字符',trigger:'blur'}
          ]
        }
      }
    },
    methods:{
      onSubmit(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.$axios.post('/login',this.form).then(res=>{
              console.log(res);
              console.log(res);
              if(res.data.code == 200){
                this.$store.commit('setUserId',res.data.obj);
                this.$router.replace("/home")
              }else{
                alert(res.data.message)
              }
            }).catch(err=>{
              console.log(err);
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      onRegister(){
        this.$router.push("/register")
      }
    }
  }
</script>

<style scoped>
  .container{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .card-container{
    margin-top: 50px;
  }
  .card{
    width: 500px;
    height: 250px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

</style>